define(['ionic'], function () {
    angular.module('myApp', ['ionic'])
        .config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
            $stateProvider
                .state('home', {
                    url: '/home',
                    templateUrl: 'templates/home.html',
                    controller: 'HomeCtrl'
                })
                .state('map', {
                    url: '/map/:location',
                    templateUrl: 'templates/map.html',
                    controller: 'MapCtrl'
                })
                .state('sign', {
                    url: '/sign/:name',
                    templateUrl: 'templates/sign.html',
                    controller: 'SignCtrl'
                })

            $urlRouterProvider.otherwise('/home');

            $ionicConfigProvider.platform.android.navBar.alignTitle('center');
            $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.android.navBar.transition('view');
            $ionicConfigProvider.platform.android.views.transition('ios');
            $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
            $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
            $ionicConfigProvider.platform.android.tabs.style('standard');
            $ionicConfigProvider.platform.android.tabs.position('bottom');
            $ionicConfigProvider.platform.android.form.toggle('large');

            $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
            $ionicConfigProvider.platform.default.backButton.text(false);
        })
        .run(function () {
            u9.hideLoading();
        })
        .filter('filterDate', function () {
            return function (e) {
                return e.substring(e.indexOf(" "));
            }
        })
        .factory('Home', function ($q) {
            var Data = {
                UserCode: u9.getLoginData().UserCode + '',
                UserOrgId: u9.getLoginData().OrgId + '',
                SignData2: [
                    {
                        date: '2016-01-11',
                        detail: [{
                            time: "2016-01-11 08:30:30",
                            place: "用友软件园",
                            ID: 1
                        }, {
                            time: "2016-01-11 16:30:30",
                            place: "用友软件园-北门",
                            ID: 2
                        }]
                    },
                    {
                        date: '2016-01-12',
                        detail: [{
                            time: "2016-01-12 08:31:30",
                            place: "用友软件园",
                            ID: 3
                        }, {
                            time: "2016-01-12 16:31:30",
                            place: "用友软件园-北门",
                            ID: 4
                        }]
                    }],
                SignData: [{
                    time: "2016-01-11 08:30:30",
                    place: "用友软件园",
                    ID: 1
                }, {
                    time: "2016-01-11 16:30:30",
                    place: "用友软件园-北门",
                    ID: 2
                }, {
                    time: "2016-01-12 08:30:30",
                    place: "用友软件园-南门",
                    ID: 3
                }, {
                    time: "2016-01-12 16:30:30",
                    place: "用友软件园",
                    ID: 4
                }, {
                    time: "2016-01-14 08:30:30",
                    place: "用友软件园-北门",
                    ID: 5
                }, {
                    time: "2016-01-15 16:30:30",
                    place: "用友软件园",
                    ID: 6
                }]
            };
            ////单层list
            //function getSignDatas() {
            //    var deferred = $q.defer();
            //    var signData = [];
            //    var currentDataTimeInt = 0;//当前日期
            //    Data.SignData.forEach(function (sign) {
            //            var time = sign.time;
            //            var dataTime = time.substring(0, time.indexOf(" "));
            //            if (currentDataTimeInt == 0) {
            //                currentDataTimeInt = parseInt(dataTime.replace(/-/g, ""));
            //                signData.push({
            //                    date: dataTime
            //                });
            //            }
            //            else {
            //                if (currentDataTimeInt - parseInt(dataTime.replace(/-/g, "")) == 0) {
            //
            //                }
            //                else {
            //                    currentDataTimeInt = parseInt(dataTime.replace(/-/g, ""));
            //                    signData.push({
            //                        date: dataTime
            //                    });
            //                }
            //            }
            //            signData.push(sign);
            //        }
            //    );
            //    deferred.resolve(signData);
            //    return deferred.promise;
            //}
            //双层list
            function getSignDatas() {
                var deferred = $q.defer();
                var signData = [];
                    var currentDataTimeInt = 0;//当前日期
                    var currentIndex = 0;
                    Data.SignData.forEach(function (sign) {
                            var time = sign.time;
                            var dataTime = time.substring(0, time.indexOf(" "));
                            if (currentDataTimeInt == 0) {
                                currentDataTimeInt = parseInt(dataTime.replace(/-/g, ""));
                                signData.push({
                                    date: dataTime,
                                    detail:[sign]
                                });
                            }
                            else {
                                if (currentDataTimeInt - parseInt(dataTime.replace(/-/g, "")) == 0) {
                                    signData[currentIndex].detail.push(sign);
                                }
                                else {
                                    currentDataTimeInt = parseInt(dataTime.replace(/-/g, ""));
                                    signData.push({
                                        date: dataTime,
                                        detail:[sign]
                                    });
                                    currentIndex++;
                                }
                            }

                        }
                    );
                deferred.resolve(signData);
                return deferred.promise;
            }

            //获取网络用户数据(usercode)
            function getUserData() {
                var deferred = $q.defer();
                u9.showLoading();
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IGetUserNameAndDesByCode',
                    params: [],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        Data.userData.userName = data.Name;
                        Data.userData.departmentName = data.Des;
                        //Data.userData.userImage = userdata.Seal;
                        deferred.resolve(Data.userData);
                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                });
                return deferred.promise;
            }

            //获取用户部门信息
            function getUserDepartment() {
                var deferred = $q.defer();
                u9.showLoading();
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IGetDeptInfo',
                    params: [],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        Data.userData.departmentName = data.Name;
                        Data.userData.departmentId = data.ID;
                        deferred.resolve(Data.userData);
                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                });
                return deferred.promise;
            }

            // 在133服务器使用
            ////获取网络用户数据(usercode)
            //function getUserData() {
            //    var deferred = $q.defer();
            //    u9.showLoading();
            //    u9.callSV({
            //        name: 'UFIDA.U9.ISV.MFGRestContactSV.Contact.IGetDepOperaterInfo',
            //        params: [Data.UserCode],
            //        onSuccess: function (data) {
            //            u9.hideLoading();
            //            var userdata =  data[0];
            //            Data.userData.userName = userdata.OperaterName;
            //            Data.userData.departmentName = userdata.Depterment;
            //            Data.userData.userImage = userdata.Seal;
            //            deferred.resolve(Data.userData);
            //        },
            //        onFailure: function (err) {
            //            u9.hideLoading();
            //            console.log(err);
            //            deferred.reject(err);
            //        }
            //    });
            //    return deferred.promise;
            //}

            //获取内存用户数据
            function getLocalUserData() {
                return Data.userData;
            }

            return {
                getUserData: getUserData,
                getLocalUserData: getLocalUserData,
                getUserDepartment: getUserDepartment,
                getSignDatas: getSignDatas
            }
        })
        .factory('Map', function ($q,$http) {

            //提交签到数据(用户编码，时间，组织id，地点，省，市，段1，段2)
            function getLocationData(query, location, radius,page_size, output,ak) {
                var deferred = $q.defer();
                u9.showLoading();
                $http({
                    method: 'POST',
                    url: 'http://api.map.baidu.com/place/v2/search',
                    params: {
                        'query': query,
                        'location': location,
                        'radius': radius,
                        'page_size':page_size,
                        'output': output,
                        'ak': ak
                    }
                }).success(function(data) {
                    u9.hideLoading();
                    deferred.resolve(data);
                }).error(function(data) {
                    alert(data);
                });
                return deferred.promise;
            }

            return {
                getLocationData: getLocationData
            }
        })

        .factory('Report', function ($q) {
            var Data = {
                UserCode: u9.getLoginData().UserCode + '',
                UserOrgId: u9.getLoginData().OrgId + '',
                projects: [{
                    ID: 1,
                    Name: "项目1"
                }, {
                    ID: 2,
                    Name: "项目2"
                }, {
                    ID: 3,
                    Name: "项目3"
                }]
            };

            function submitReportData(projectId, projectName, deptId, apm, hour, content, time, isFillIn, state) {
                var deferred = $q.defer();
                u9.showLoading();
                var reportData = [{
                    //ID:null,
                    Project: projectId,
                    ProjectName: projectName,
                    Org: Data.UserOrgId,
                    Dept: deptId,
                    TimeSlotEnum: apm,
                    ManHour: hour,
                    WorkContent: content,
                    UserCode: Data.UserCode,
                    OperationDate: time,
                    IsFillIn: isFillIn,
                    StateEnum: state
                }]
                var jsonData = {
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.ICreateWorkSV',
                    params: [reportData],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        deferred.resolve(data);
                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                };
                u9.callSVAlone(jsonData);
                return deferred.promise;
            }

            function updateReportData(reportId, projectId, projectName, deptId, apm, hour, content, time, isFillIn, state) {
                var deferred = $q.defer();
                u9.showLoading();
                var reportData = [{
                    ID: reportId,
                    Project: projectId,
                    ProjectName: projectName,
                    Org: Data.UserOrgId,
                    Dept: deptId,
                    TimeSlotEnum: apm,
                    ManHour: hour,
                    WorkContent: content,
                    UserCode: Data.UserCode,
                    OperationDate: time,
                    IsFillIn: isFillIn,
                    StateEnum: state
                }]
                var jsonData = {
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IUpdateWorkSV',
                    params: [reportData],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        deferred.resolve(data);
                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                };
                u9.callSVAlone(jsonData);
                return deferred.promise;
            }

            //获取每日汇报数据(开始时间，结束时间，人员编码，状态)
            function getDayReportData(startTime, endTime) {
                var deferred = $q.defer();
                u9.showLoading();
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IQueryWorkInfo',
                    params: [startTime, endTime, Data.UserCode, -1],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        console.log(data);
                        deferred.resolve(data);
                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                });
                return deferred.promise;
            }

            //根据简称搜索获取项目列表()
            function searchProject(search) {
                var deferred = $q.defer();
                u9.showLoading();
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IQueryProjectInfo',
                    params: [search],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        console.log(data);
                        deferred.resolve(data);

                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                });
                return deferred.promise;
            }

            //获取历史项目列表()
            function getHistoryProject() {
                var deferred = $q.defer();
                u9.showLoading();
                u9.callSV({
                    name: 'UFIDA.U9.ISV.MFGLBSSV.LBS.IGetHistoryProj',
                    params: [],
                    onSuccess: function (data) {
                        u9.hideLoading();
                        console.log(data);
                        deferred.resolve(data);

                    },
                    onFailure: function (err) {
                        u9.hideLoading();
                        console.log(err);
                        deferred.reject(err);
                    }
                });
                return deferred.promise;
            }

            return {
                submitReportData: submitReportData,
                getDayReportData: getDayReportData,
                searchProject: searchProject,
                updateReportData: updateReportData,
                getHistoryProject: getHistoryProject
            }
        })

        .filter('filterApm', function () {
            return function (e) {
                if (e == 1) {
                    return "上午";
                }
                else if (e == 2) {
                    return "下午";
                }
                else if (e == 3) {
                    return "全天";
                }
                return "上午";
            }
        })


        .controller('HomeCtrl', function ($scope, $state, Home) {

            var lat = "";//纬度
            var lon = "";//经度
            $scope.sign_data = [];

            //初始化，消息按钮按下，显示消息
            $scope.initButtonActive = function () {
                $scope.btn = {
                    checked: false,
                    defaultbtnleft: 'btn-left',
                    defaultbtnright: 'btn-right'
                }
            };

            var EARTH_RADIUS = 6378137.0;    //单位M
            var PI = Math.PI;

            function getRad(d){
                return d*PI/180.0;
            }
            //取地球任意两点经纬度的距离
            function getFlatternDistance(lat1,lng1,lat2,lng2){
                var f = getRad((lat1 + lat2)/2);
                var g = getRad((lat1 - lat2)/2);
                var l = getRad((lng1 - lng2)/2);

                var sg = Math.sin(g);
                var sl = Math.sin(l);
                var sf = Math.sin(f);

                var s,c,w,r,d,h1,h2;
                var a = EARTH_RADIUS;
                var fl = 1/298.257;

                sg = sg*sg;
                sl = sl*sl;
                sf = sf*sf;

                s = sg*(1-sl) + (1-sf)*sl;
                c = (1-sg)*(1-sl) + sf*sl;

                w = Math.atan(Math.sqrt(s/c));
                r = Math.sqrt(s*c)/w;
                d = 2*w*a;
                h1 = (3*r -1)/2/c;
                h2 = (3*r +1)/2/s;

                return d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
            }
            $scope.changeActive = function (type) {
                //内勤签到
                if (type == 0) {
                    $scope.btn = {
                        checked: true,
                        defaultbtnleft: 'btn-left',
                        defaultbtnright: 'btn-right'
                    };
                    signIn();
                }
                //外勤签到
                else if (type == 1) {
                    $scope.btn = {
                        checked: false,
                        defaultbtnleft: 'btn-left-active',
                        defaultbtnright: 'btn-right-active'
                    };
                    signIn();
                    //$state.go("map", {
                    //    location: 40.073653+","+116.240388
                    //});
                }
            };

            function successToDo() {
                //内勤
                if($scope.btn.checked){
                    //我的工位的点40.073653 116.240388
                    //用友软件园中心点40.072692,116.240894
                    var distance = getFlatternDistance(lat,lon,40.072692,116.240894);
                    //var distance = getFlatternDistance(lat,lon,40.072692,116.240894);
                    alert(distance);
                    if(distance<1000){
                        u9.alert("签到成功");
                    }
                    else{
                        u9.alert("不在公司范围内，签到失败");
                    }
                }
                else{
                    $state.go("map", {
                        location: lat+","+lon
                    });
                }
            }
            var onSuccess = function(position) {
                lat = position.coords.latitude;
                lon = position.coords.longitude;
                successToDo();
            };
            
            function onError(error) {
                alert('code: '    + error.code    + '\n' +
                'message: ' + error.message + '\n');
            }

            function successCallback(data) {
                u9.hideLoading();
                lat = data.substring(data.indexOf("latitude")+10,data.indexOf("lontitude"));
                lon = data.substring(data.indexOf("lontitude")+11,data.indexOf("radius"));
                lat = lat.replace(/\n/g,"").replace(/ /g,"");
                lon = lon.replace(/\n/g,"").replace(/ /g,"");
                lat = parseFloat(lat);
                lon = parseFloat(lon);
                successToDo();
            };
            function failedCallback(error) {
                u9.hideLoading();
                alert("error"+error);
            }

            //签到（获取所在位置信息，与用友的位置信息的直线距离绝对值小于1000,即在公司范围内）
            function signIn() {
                u9.showLoading();

                if(parent.device.platform == "Android") {
                    parent.baidu_location.getCurrentPosition(successCallback, failedCallback);
                }
                else{
                    parent.navigator.geolocation.getCurrentPosition(onSuccess, onError);
                }
            }

            Home.getSignDatas().then(function (data) {
                $scope.sign_data = data;
            });
            $scope.sign = function () {
                $state.go("sign", {});
            };

            $scope.initData = function () {
                $scope.initButtonActive();
                //$scope.doRefresh();
            };

            $scope.initData();
        })
        .controller('MapCtrl', function ($scope,$stateParams,Map,$state) {
            $scope.places = [];
            var lon ;
            var lat ;
            var query = "公司";
            var location = $stateParams.location;
            var radius = 1000;
            var page_size = 20;
            var output = "json";
            var ak = "4fnwY1lCfnnoW3a55aKaMf9g";

            var lon_lat =  $stateParams.location.split(",")
            lat = lon_lat[0];
            lon = lon_lat[1];
            // 百度地图API功能
            var map = new BMap.Map("allmap",{minZoom:16,maxZoom:20});
            map.centerAndZoom(new BMap.Point(lon,lat),11);
            map.enableScrollWheelZoom(true);
            //// 用经纬度设置地图中心点
            //function theLocation(){
            //    map.clearOverlays();
            //    var new_point = new BMap.Point(lon,lat);
            //    var marker = new BMap.Marker(new_point);  // 创建标注
            //    map.addOverlay(marker);              // 将标注添加到地图中
            //    map.panTo(new_point);
            //}
            // 编写自定义函数,创建标注
            function addMarker(point){
                var marker = new BMap.Marker(point);
                map.addOverlay(marker);
            }
            $scope.getOnePlaceSign = function (item){
                $state.go("sign", {
                    name: item.name
                });
            }
            Map.getLocationData(query, location, radius,page_size, output,ak).then(function (data) {
                if (data.results && data.results.length > 0) {
                    $scope.places = data.results;
                    for (var i = 0; i < $scope.places.length; i++) {
                        var point = new BMap.Point($scope.places[i].location.lng, $scope.places[i].location.lat);
                        addMarker(point);
                    }
                }
                else {

                }
            });

        })
        .controller('SignCtrl', function ($scope,$stateParams) {

            $scope.locationName = $stateParams.name;

        })


    angular.element(document).ready(function () {
        angular.bootstrap(document, ['myApp']);
    });
});